import type { Cloud } from '@/type'
import fetchJSONP from 'fetch-jsonp'
import { Images, Issues } from '@/type'

const CLOUD_API = 'https://v1.yiketianqi.com/free/day?appid=22926531&appsecret=pqo8JVmE&unescape=1'
const getV5ReposOwnerRepoIssues =
  'https://gitee.com/api/v5/repos/SingerLan/image-bed/issues?access_token=094444a90b70fb5767a1e1d7264a79a3&state=open&sort=created&direction=desc&page={page}&per_page=10'
const getDoubanUrl = 'https://douban.singerlan.repl.co/douban.php?callback=list&type=movie&from='
export const queryCloud = async (): Promise<Cloud> => {
  try {
    const response = await fetch(CLOUD_API)
    if (response.ok) {
      return await response.json()
    } else {
      const error = new Error(response.statusText)
      return Promise.reject(error)
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

export const queryIssues = async (page: number): Promise<Issues[]> => {
  try {
    const response = await fetch(getV5ReposOwnerRepoIssues.replace('{page}', String(page)))
    if (response.ok) {
      return await response.json()
    } else {
      const error = new Error(response.statusText)
      return Promise.reject(error)
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

export const queryDouban = async (page: number): Promise<Images[]> => {
  try {
    const data = await fetchJSONP(getDoubanUrl + page).then((response) => response.json())
    return data
  } catch (error) {
    return Promise.reject(error)
  }
}
